//this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

// FileDetailDialog.cpp : implementation file
//

//#include "stdafx.h"
#include "wintypes.h"
#include "emule.h"
#include "FileDetailDialog.h"
#include "otherfunctions.h"
//#include "FileInfoDialog.h"
#include "CommentDialogLst.h"
#include "muuli_wdr.h"

#include "wx/xrc/xmlres.h"
#include "wx/xrc/xh_all.h"

#define SYSCOLOR(x) (wxSystemSettings::GetColour(x))

// CFileDetailDialog dialog
#define GetDlgItem(x,clas) XRCCTRL(*this,#x,clas)
#define IsDlgButtonChecked(x) XRCCTRL(*this,#x,wxCheckBox)->GetValue()
#define CheckDlgButton(x,y) XRCCTRL(*this,#x,wxCheckBox)->SetValue(y)

#define ID_MY_TIMER 1652

//IMPLEMENT_DYNAMIC(CFileDetailDialog, CDialog)
BEGIN_EVENT_TABLE(CFileDetailDialog,wxDialog)
  EVT_BUTTON(ID_CLOSEWND,CFileDetailDialog::OnClosewnd)

  EVT_BUTTON(XRCID("IDC_BUTTONSTRIP"), CFileDetailDialog::OnBnClickedButtonStrip)
  EVT_BUTTON(XRCID("IDC_TAKEOVER"), CFileDetailDialog::TakeOver)	
  EVT_BUTTON(XRCID("IDC_FILEINFO"), CFileDetailDialog::OnBnClickedFileinfo)
  EVT_BUTTON(XRCID("IDC_CMTBT"), CFileDetailDialog::OnBnClickedShowComment) //for comment
  EVT_BUTTON(XRCID("IDC_RENAME"), CFileDetailDialog::Rename) // Added by Tarod [Juanjo]

  EVT_TIMER(ID_MY_TIMER,CFileDetailDialog::OnTimer)
END_EVENT_TABLE()

CFileDetailDialog::CFileDetailDialog(wxWindow* parent,CPartFile* file)
  //: CDialog(CFileDetailDialog::IDD, 0)
  : wxDialog(parent,9998,"File Details",wxDefaultPosition,wxDefaultSize,wxDEFAULT_DIALOG_STYLE|wxSYSTEM_MENU)
{
  //wxSizer* content=fileDetails(this,TRUE);
  //content->Show(this,TRUE);

  SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));

  wxPanel* content=wxXmlResource::Get()->LoadPanel(this,"DLG_FILEDETAILS");
  wxSize koko=content->GetSize();
  //koko.SetHeight(koko.GetHeight()-120);
  SetSize(content->GetSize()); //koko);

  // oops this too..
  content->SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));

  Centre();

  m_file = file;

  m_timer.SetOwner(this,ID_MY_TIMER);
  m_timer.Start(5000);

  Localize();
  UpdateData();
}

CFileDetailDialog::~CFileDetailDialog()
{
  m_timer.Stop();
}

void CFileDetailDialog::OnTimer(wxTimerEvent& evt) {
	UpdateData();
}

#if 0
void CFileDetailDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BOOL CFileDetailDialog::OnInitDialog(){
	CDialog::OnInitDialog();
	Localize();
	m_timer=SetTimer(301, 5000, 0);
	UpdateData();

	return true;
}
#endif

void CFileDetailDialog::OnClosewnd(wxCommandEvent& evt)
{
  EndModal(0);
}

void CFileDetailDialog::UpdateData(){
	CString bufferS;

	GetDlgItem(IDC_FNAME,wxControl)->SetLabel(MakeStringEscaped(m_file->GetFileName()));
	GetDlgItem(IDC_METFILE,wxControl)->SetLabel(m_file->GetFullName());
	wxString tmp=GetDlgItem(IDC_FILENAME,wxTextCtrl)->GetValue();
	if (tmp.Length()<3)
		GetDlgItem(IDC_FILENAME,wxTextCtrl)->SetValue(m_file->GetFileName());

	GetDlgItem(IDC_FHASH,wxTextCtrl)->SetValue(EncodeBase16(m_file->GetFileHash(), 16));

	GetDlgItem(IDC_FSIZE,wxControl)->SetLabel(CastItoXBytes(m_file->GetFileSize()));

	GetDlgItem(IDC_PFSTATUS,wxControl)->SetLabel(m_file->getPartfileStatus());
	
	bufferS.Format("%i(%i)",m_file->GetPartCount(),m_file->GetHashCount());
	GetDlgItem(IDC_PARTCOUNT,wxControl)->SetLabel(bufferS);

	GetDlgItem(IDC_TRANSFERED,wxControl)->SetLabel(CastItoXBytes(m_file->GetTransfered()));

	bufferS.Format(GetResString(IDS_FD_STATS),CastItoXBytes(m_file->GetLostDueToCorruption()).GetData(), CastItoXBytes(m_file->GetGainDueToCompression()).GetData(), m_file->TotalPacketsSavedDueToICH() );
	GetDlgItem(IDC_FD_STATS,wxControl)->SetLabel(bufferS);

	GetDlgItem(IDC_COMPLSIZE,wxControl)->SetLabel(CastItoXBytes(m_file->GetCompletedSize()));

	bufferS.Format("%.2f ",m_file->GetPercentCompleted());
	GetDlgItem(IDC_PROCCOMPL,wxControl)->SetLabel(bufferS+GetResString(IDS_PROCDONE));

	bufferS.Format("%.2f %s",(float)m_file->GetDatarate()/1024,GetResString(IDS_KBYTESEC).GetData());
	GetDlgItem(IDC_DATARATE,wxControl)->SetLabel(bufferS);

	bufferS.Format("%i",m_file->GetSourceCount());
	GetDlgItem(IDC_SOURCECOUNT,wxControl)->SetLabel(bufferS);
	bufferS.Format("%i",m_file->GetTransferingSrcCount());
	GetDlgItem(IDC_SOURCECOUNT2,wxControl)->SetLabel(bufferS);

	bufferS.Format("%i (%.1f%%)",m_file->GetAvailablePartCount(),(float) ((m_file->GetAvailablePartCount()*100)/ m_file->GetPartCount()));
	GetDlgItem(IDC_PARTAVAILABLE,wxControl)->SetLabel(bufferS);

	if (m_file->lastseencomplete==0) bufferS.Format(GetResString(IDS_UNKNOWN).MakeLower()); else {
	  char tmps[80];
	  strftime(tmps,sizeof(tmps),"%A, %x, %X",localtime(&m_file->lastseencomplete));
	  bufferS=tmps;//.Format( "%s",m_file->lastseencomplete.Format( "%A, %x, %X"));
	}

	GetDlgItem(IDC_LASTSEENCOMPL,wxControl)->SetLabel(bufferS);
	GetDlgItem(IDC_RENAME,wxControl)->Enable((m_file->GetStatus() == PS_COMPLETE || m_file->GetStatus() == PS_COMPLETING) ? false:true);//add by CML 
	GetDlgItem(IDC_FILEINFO,wxControl)->Enable(m_file->IsMovie()); // added by quekky
}

#if 0
void CFileDetailDialog::OnDestroy() {
	 if (m_timer) KillTimer(m_timer);
}

BEGIN_MESSAGE_MAP(CFileDetailDialog, CDialog)
	ON_WM_TIMER()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTONRENAME, OnBnClickedButtonrename) // Added by Tarod [Juanjo]
	ON_BN_CLICKED(IDC_BUTTONSTRIP, OnBnClickedButtonStrip)
	ON_BN_CLICKED(IDC_TAKEOVER, TakeOver)	
END_MESSAGE_MAP()
#endif

// CFileDetailDialog message handlers

#define LVCFMT_LEFT wxLIST_FORMAT_LEFT

void CFileDetailDialog::Localize(){
	GetDlgItem(IDC_FD_X0,wxControl)->SetLabel(GetResString(IDS_FD_GENERAL));
	GetDlgItem(IDC_FD_X1,wxControl)->SetLabel(GetResString(IDS_FD_NAME));
	GetDlgItem(IDC_FD_X2,wxControl)->SetLabel(GetResString(IDS_FD_MET));
	GetDlgItem(IDC_FD_X3,wxControl)->SetLabel(GetResString(IDS_FD_HASH));
	GetDlgItem(IDC_FD_X4,wxControl)->SetLabel(GetResString(IDS_FD_SIZE));
	GetDlgItem(IDC_FD_X5,wxControl)->SetLabel(GetResString(IDS_FD_STATUS));
	GetDlgItem(IDC_FD_X6,wxControl)->SetLabel(GetResString(IDS_FD_TRANSFER));
	GetDlgItem(IDC_FD_X7,wxControl)->SetLabel(GetResString(IDS_FD_SOURCES));
	GetDlgItem(IDC_FD_X10,wxControl)->SetLabel(GetResString(IDS_FD_TRANSI));
	GetDlgItem(IDC_FD_X9,wxControl)->SetLabel(GetResString(IDS_FD_PARTS));
	GetDlgItem(IDC_FD_X14,wxControl)->SetLabel(GetResString(IDS_FD_TRANS));
	GetDlgItem(IDC_FD_X12,wxControl)->SetLabel(GetResString(IDS_FD_COMPSIZE));
	GetDlgItem(IDC_FD_X13,wxControl)->SetLabel(GetResString(IDS_FD_DATARATE));
	GetDlgItem(IDC_FD_X11,wxControl)->SetLabel(GetResString(IDS_AVAIL)+":");
	GetDlgItem(IDC_FD_X15,wxControl)->SetLabel(GetResString(IDS_LASTSEENCOMPL));
	GetDlgItem(IDC_TAKEOVER,wxControl)->SetLabel(GetResString(IDS_TAKEOVER));
	GetDlgItem(IDC_BUTTONSTRIP,wxControl)->SetLabel(GetResString(IDS_CLEANUP));
	GetDlgItem(IDC_RENAME,wxControl)->SetLabel(GetResString(IDS_RENAME));
	GetDlgItem(IDC_FD_SN,wxControl)->SetLabel(GetResString(IDS_SOURCENAMES));
	GetDlgItem(IDC_FILEINFO,wxControl)->SetLabel(GetResString(IDS_FILEINFO));
	GetDlgItem(IDC_CMTBT,wxControl)->SetLabel(GetResString(IDS_CMT_SHOWALL));//For Comment 		

	//GetDlgItem(IDOK,wxControl)->SetLabel(GetResString(IDS_FD_CLOSE));
	//SetWindowText(GetResString(IDS_FD_TITLE));
	FillSourcenameList();

}

void CFileDetailDialog::FillSourcenameList() {
   // by Juanjo
   POSITION pos1,pos2; 
   CUpDownClient* cur_src; 
   wxListCtrl* pmyListCtrl; 
   //LVFINDINFO info; 
   //info.flags = LVFI_STRING; 
   int itempos; 
   int namecount; 
   
   CString nameCountStr; 
   pmyListCtrl = (wxListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES,wxListCtrl); 
   if (pmyListCtrl->GetColumnCount() < 2) { 
     //pmyListCtrl->DeleteColumn(0); 
     pmyListCtrl->InsertColumn(0, GetResString(IDS_DL_FILENAME), LVCFMT_LEFT, 340); 
     pmyListCtrl->InsertColumn(1, GetResString(IDS_DL_SOURCES), LVCFMT_LEFT, 60); 
   }
   
   CString strText; 
   pmyListCtrl->DeleteAllItems(); 
   for (int sl=0;sl<SOURCESSLOTS;sl++) if (!m_file->srclists[sl].IsEmpty())
   for (pos1 = m_file->srclists[sl].GetHeadPosition(); (pos2 = pos1) != NULL;) { 
      m_file->srclists[sl].GetNext(pos1); 
      cur_src = m_file->srclists[sl].GetAt(pos2); 
      //info.psz = cur_src->GetClientFilename(); 
      if (cur_src->GetClientFilename() != 0) { 
         if ((itempos=pmyListCtrl->FindItem(-1,wxString(cur_src->GetClientFilename()))) == -1) { 
            int itemid=pmyListCtrl->InsertItem(0, cur_src->GetClientFilename()); 
            pmyListCtrl->SetItem(0, 1, "1"); 
            pmyListCtrl->SetItemData(0, 1); 

	    // background.. argh
	    wxListItem tmpitem;
	    tmpitem.m_itemId=itemid;
	    tmpitem.SetBackgroundColour(SYSCOLOR(wxSYS_COLOUR_LISTBOX));
	    pmyListCtrl->SetItem(tmpitem);
         } else { 
            namecount = (pmyListCtrl->GetItemData(itempos)); 
            namecount ++; 
            nameCountStr.Format("%i", namecount); 
            pmyListCtrl->SetItem(itempos, 1, nameCountStr); 
            pmyListCtrl->SetItemData(itempos, namecount); 
         } 
	 //pmyListCtrl->SortItems(CompareListNameItems, 11); 
	 //	m_SortAscending[0] =true;m_SortAscending[1] =false;
      } 
   } 
   // End by Juanjo
}

#if 0
void CFileDetailDialog::OnBnClickedButtonrename() 
{ 
   CString NewFileName; 
   GetDlgItem(IDC_FILENAME)->GetWindowText(NewFileName);

   m_file->SetFileName(NewFileName.GetBuffer()); 
   m_file->SavePartFile(); 

   GetDlgItem(IDC_FNAME)->SetWindowText(m_file->GetFileName());
   GetDlgItem(IDC_METFILE)->SetWindowText(m_file->GetFullName());
   GetDlgItem(IDC_FILENAME)->SetWindowText(m_file->GetFileName());
} 

int CALLBACK CFileDetailDialog::CompareListNameItems(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{ 
	if (lParam1 == lParam2) return 0; 
	if (lParam1 > lParam2) return -1; else return 1; 
} 
#endif

void CFileDetailDialog::OnBnClickedShowComment(wxEvent& evt)
{
  CCommentDialogLst* dialog=new CCommentDialogLst(this,m_file);
  dialog->ShowModal();
  delete dialog;
}

void CFileDetailDialog::Rename(wxEvent& evt) 
{ 
   wxString NewFileName; 
   NewFileName=GetDlgItem(IDC_FILENAME,wxTextCtrl)->GetValue();

   m_file->SetFileName((char*)NewFileName.GetData()); 
   m_file->SavePartFile(); 

   GetDlgItem(IDC_FNAME,wxControl)->SetLabel(m_file->GetFileName());
   GetDlgItem(IDC_METFILE,wxControl)->SetLabel(m_file->GetFullName());
   GetDlgItem(IDC_FILENAME,wxTextCtrl)->SetValue(m_file->GetFileName());
} 

void CFileDetailDialog::OnBnClickedButtonStrip(wxEvent& evt) {
	wxString filename,tempStr;
	char c;

	filename=GetDlgItem(IDC_FILENAME,wxTextCtrl)->GetValue();
	
	// Replace . with Spaces - except the last one (extention-dot)
	int extpos=filename.Find('.',TRUE);
	if (extpos>=0) {
		filename.Replace("."," ");
		filename.SetChar(extpos,'.');
	}

	// Replace Space-holders with Spaces
	filename.Replace("_"," ");
	filename.Replace("%20"," ");

	// Barry - Some additional formatting
	filename.MakeLower();
	filename.Replace("sharereactor", "");
	filename.Replace("deviance", "");
	filename.Replace("-ftv", "");
	filename.Replace("flt", "");
	filename.Replace("[]", "");
	filename.Replace("()", "");
	filename.Replace("  ", " ");

	// Make leading Caps 
	if (filename.Length()>1)
	{
		tempStr=filename.GetChar(0);
		tempStr.MakeUpper();
		c = tempStr.GetChar(0);
		filename.SetChar(0, c);
		
		for (int ix=0; ix<filename.Length()-1; ix++)
		{
			if (filename.GetChar(ix) == ' ') 
			{
				tempStr=filename.GetChar(ix+1);
				tempStr.MakeUpper();
				c=tempStr.GetChar(0);
				filename.SetChar(ix+1,c);
			}
		}
	}

	GetDlgItem(IDC_FILENAME,wxTextCtrl)->SetValue(MakeStringEscaped(CString(filename.GetData())));
}

// added by quekky
void CFileDetailDialog::OnBnClickedFileinfo(wxEvent& evt)
{
  //CFileInfoDialog dialog(m_file);
  //dialog.DoModal();
}

void CFileDetailDialog::TakeOver(wxEvent& evt) {
   wxListCtrl* pmyListCtrl; 
   int itemPosition; 

   pmyListCtrl = (wxListCtrl*)GetDlgItem(IDC_LISTCTRLFILENAMES,wxListCtrl);
   if (pmyListCtrl->GetSelectedItemCount() > 0) {
     long pos=-1;
     for(;;) {
       pos=pmyListCtrl->GetNextItem(pos,wxLIST_NEXT_ALL,wxLIST_STATE_SELECTED);
       if(pos==-1)
	 break;
       //POSITION pos = pmyListCtrl->GetFirstSelectedItemPosition(); 
       //itemPosition = pmyListCtrl->GetNextSelectedItem(pos); 
       GetDlgItem(IDC_FILENAME,wxTextCtrl)->SetValue(pmyListCtrl->GetItemText(pos));
     }
   } 
}
